import React, { createContext, useContext, useState, ReactNode } from 'react';

// 用户数据类型
interface User {
  id: string;
  name: string;
  email?: string;
  avatar?: string;
}

// 用户上下文值类型
interface UserContextValue {
  user: User | null;
  setUser: (user: User | null) => void;
  clearUser: () => void;
}

// 创建用户上下文
const UserContext = createContext<UserContextValue | undefined>(undefined);

// 用户 Provider 组件
export const UserProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);

  const clearUser = () => setUser(null);

  return (
    <UserContext.Provider value={{ user, setUser, clearUser }}>
      {children}
    </UserContext.Provider>
  );
};

// 自定义 Hook：方便组件消费用户上下文
export const useCurrentUser = (): UserContextValue => {
  const context = useContext(UserContext);
  if (!context) {
    throw new Error('useUser 必须在 UserProvider 内部使用');
  }
  return context;
};

export default UserProvider;